import constants as con
import pygame
import pymunk 
import math, sys, random
from pygame.color import *

class Platform(pygame.sprite.Sprite):
    image = None

    def __init__(self,parent):
        pygame.sprite.Sprite.__init__(self)

        self.parent = parent

        if Platform.image is None:
            Platform.image = con.load_image('dat_beam.png')

        self.friction = 0.5
        self.inertia = 200
        self.mass = 1
        self.elasticity = 0

        self.centerX = int(con.window_size[0] / 2)
        self.centerY = int((con.window_size[1] / 2) * 0.7)
        self.length = int(con.window_size[0] * 0.8) / 2

        self.master = pygame.transform.scale(Platform.image, (self.length * 2, 10))

        # let's make some physics
        spring_anchor_left = pymunk.Body(pymunk.inf,pymunk.inf)
        spring_anchor_left.position = (self.centerX - self.length , self.centerY - 60)
        self.lpos = spring_anchor_left.position

        spring_anchor_right = pymunk.Body(pymunk.inf,pymunk.inf)
        spring_anchor_right.position = (self.centerX + self.length, self.centerY - 60)
        self.rpos = spring_anchor_right.position

        slide_constraint = pymunk.Body(pymunk.inf,pymunk.inf)
        slide_constraint.position = (self.centerX, self.centerY)
        self.cpos = slide_constraint.position

        offset = 0
        platform_points = [(-self.length, 0 - offset), (self.length, 0 - offset), (self.length, -10.0 - offset), (-self.length, -10.0 - offset)]

        self.body = pymunk.Body(self.mass,self.inertia)
        self.body.position = (self.centerX,self.centerY)

        self.platform = pymunk.Poly(self.body, platform_points, (0,0))
        self.platform.layers = 1 | 2
        self.platform.friction = self.friction
        self.platform.elasticity = self.elasticity

        spring_left = pymunk.DampedSpring(self.body, spring_anchor_left, (-self.length,0), (0,0), 100, 1, 5)
        spring_right = pymunk.DampedSpring(self.body, spring_anchor_right, (self.length,0), (0,0), 70, 5, 5)
        slide_constraint = pymunk.PinJoint(self.body, slide_constraint, (0,0), (0,0))


        self.rect = pygame.Rect(0,0,self.length * 2, 20)
        self.rect.center = (self.centerX, con.flipy(self.centerY - 5))

        self.parent.space.add(self.body, self.platform, spring_left, spring_right, slide_constraint)
        self.parent.sprites.add(self)

    def update(self):
        center = self.rect.center
        #buf =  con.to_pygame(self.body.position + self.body.rotation_vector)
        #self.rect.topleft = buf
        self.image = pygame.transform.rotate(self.master, math.degrees(self.body.angle))
        self.rect = self.image.get_rect()
        self.rect.center = center

    def pymunkDraw(self,screen):
        ps = self.platform.get_points()
        ps.append(ps[0])
        ps = map(con.to_pygame,ps)
        pygame.draw.lines(screen, THECOLORS["lightgray"], False, ps, 1)
                                                
